package com.lzy.cloud.url.util;

import com.lzy.cloud.url.service.ShortUrlService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 短网址工具类
 * 算法：url md5生成32位字符串，先取0-6位，若数据库中已存在该值，则将其转为大写，若还存在，右移一位取1-7位，以此类推
 */
@Component
@Slf4j
public class ShortUrlUtil {

    @Autowired
    private ShortUrlService shortUrlService;

    /**
     * 递归计数
     */
    private static int recursiveCount = 0;

    /**
     * @param targetUrl 目标url
     * @return
     */
    public String generateUrl(String targetUrl) {
        String md5Url = MD5Utils.MD5(targetUrl);
        String result = md5Url.substring(recursiveCount, recursiveCount + 6);
        if (shortUrlService.findByShortUrl(result) != null) {
            if (shortUrlService.findByShortUrl(result.toUpperCase()) == null) {
                result = result.toUpperCase();
            } else {
                recursiveCount++;
                if (recursiveCount > 26) {
                    log.error("短网址穷尽----url>" + targetUrl);
                    Ensure.that(true).isFalse("00000005");
                }
                result = generateUrl(targetUrl);
            }
        }
        return result;
    }
}
